package com.mh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mh.dao.CategoryDao;
import com.mh.dto.vo.R;
import com.mh.pojo.Category;
import com.mh.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分类表(Category)表服务实现类
 *
 * @author zmh
 * @since 2025-02-08 09:18:50
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, Category> implements CategoryService {

    @Autowired
    private CategoryDao categoryDao;

    /**
     * 分页查询
     *
     * @param page 查询页数
     * @param size 一页显示条数
     * @return ·
     */
    public R<Page<Category>> getAllByPage(int page, int size) {
        Page<Category> categoryPage = new Page<>(page, size);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //TODO 查询条件定制
        return R.success(categoryDao.selectPage(categoryPage, queryWrapper));
    }

    /**
     * 获取所有公用图标
     * @return 公用图标Map的key有三类 1.income 2.expend
     */
    @Override
    public R<Map<String, List<Category>>> getAllPublicIcon() {
        // 获取所有
        List<Category> categories = categoryDao.selectList(null);
        // 判断是否为空
        if(categories.isEmpty()){
            return R.error("暂无分类数据");
        }

        // 根据类型分出收入或支出数据
        HashMap<String, List<Category>> returnData = new HashMap<>();

        // 初始化income 和expend的Map
        categories.forEach(category -> {
            // 使用computeIfAbsent来简化逻辑，避免重复put操作
            returnData.computeIfAbsent(category.getType() == 1 ? "income" : "expend", k -> new ArrayList<>()).add(category);
        });

        return R.success(returnData);
    }
}

